<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Forpastime < forpastime@qq.com>
// +----------------------------------------------------------------------
namespace app\tenant\controller;

use app\partner\model\AreaModel;
use app\partner\model\PartnerModel;
use cmf\controller\AdminBaseController;
use think\Db;
use app\tenant\model\ShopInfoModel;
use app\tenant\validate\UserValidate;
use plugins\php_qrcode\PhpQrcodePlugin;
use plugins\php_qrcode\controller\ApiQrcodeController;
use think\Validate;
class AdminOrderController extends AdminBaseController
{
    /**
     * 商户管理
     * @adminMenu(
     *     'name'   => '商户入驻申请',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户入驻申请管理',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $keywords = $this->request->param('keywords');

        $shop_info = new ShopInfoModel();

        $list = $shop_info->getList($keywords);

        $category = Db::name('tenant_category')->where('status',1)->select()->toArray();
        $this->assign('category',$category);

        // 获取分页显示
        $page = $list->render();

        $this->assign('page',$page);
        $this->assign('list',$list);

        return $this->fetch();
    }

        /**
     * 商户管理
     * @adminMenu(
     *     'name'   => '商户入驻申请详情',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户入驻申请详情',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $id = $this->request->param('id','','intval');
        $shop_info = new ShopInfoModel();

        $shop = $shop_info->getOne($id);

        if($shop['checked']==1){
            $shop_info = Db::name('shop_apply_order')->where('shop_info_id',$shop['id'])->find();
            $admin = Db::name('user')->where('id',$shop_info['user_id'])->field('id,user_nickname,user_login')->find();
            $this->assign('tenant',$admin);
        }
        
        $category = Db::name('tenant_category')->where('status',1)->where('id',$shop['category_id'])->find();
        $this->assign('category',$category);

        $this->assign('id',$id);

        $this->assign('shop',$shop);

        return $this->fetch();
    }


    /**
     * 商户管理
     * @adminMenu(
     *     'name'   => '商户入驻审核不通过',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户入驻审核不通过',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function checkno()
    {
        $id = $this->request->param('id','','intval');
        $msg  = $this->request->param('msg','');
        $shopName  = $this->request->param('shop_name','');

        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("role_user")->where("id", $admin_id)->where('role_id','in',[1,2])->select();
        if($admin_id!=1 && !$user){
            $this->error('权限不足！');
        }

        $res = Db::name('shop_info')->where('id',$id)->update(['checked'=>2,'check_msg'=>$msg]);

        if($res){
            $partner_id = Db::name('shop_apply_order')->where('shop_info_id',$id)->value('partner_id');
            //消息通知：（待完善）
            $data = [
                'type'=>1,
                'pass'=>0,
                'content'=>empty($msg)?$shopName.'的开店申请审核未通过':$shopName.'的开店申请审核未通过。原因：'.$msg,
                'partner_id'=>$partner_id,
                'create_time'=>time()
            ];
            Db::name('partner_notice')->insertGetId($data);

            $this->success('驳回成功');
        }else{
            $this->error('驳回失败');
        }
    }

    /**
     * 商户管理
     * @adminMenu(
     *     'name'   => '商户入驻审核通过',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户入驻审核通过',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function checkok()
    {
        
        $id = $this->request->param('id','','intval');

        $shop_info = Db::name('shop_apply_order')->where('shop_info_id',$id)->where('user_id','neq','')->find();
        if($shop_info){
            $this->assign('have_admin',1);
            //直接通过

            $res = Db::name('shop_info')->where('id',$id)->update(['checked'=>1]);
            if($res){
                $this->success('审核成功!');
            }else{
                $this->success('审核失败!');

            }
        }
    }
    /**
     * 商户管理
     * @adminMenu(
     *     'name'   => '入驻审核通过填写管理员',
     *     'parent' => 'tenant/AdminIndex/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '入驻审核通过填写管理员',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function orderAdd()
    {
        $id = $this->request->param('id','','intval');

        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("role_user")->where("id", $admin_id)->where('role_id','in',[1,2])->select();
        if($admin_id!=1 && !$user){
            return $this->error('权限不足！'.json_encode($user));
        }

        $this->assign('id',$id);

        return $this->fetch();
        
        
    }
    /**
     * 商户添加提交
     * @adminMenu(
     *     'name'   => '入驻审核通过添加管理员账号',
     *     'parent' => 'addPost',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '入驻审核通过添加管理员账号',
     *     'param'  => ''
     * )
     */
    public function orderAddPost()
    {
        if ($this->request->isPost()) {
                if(!empty($_POST['role_id'])){
                    $this->error('商户用户不需要指定角色');
                }
                $admin_id = cmf_get_current_admin_id();
                $admin = DB::name('user')->where('id',$admin_id)->find();

                $rule = [
                    'user_login' => 'require|unique:user,user_login',
                    'user_pass'  => 'require',
                    'user_email' => 'require|email|unique:user,user_email',
                ];
                $message = [
                    'user_login.require' => '账户不能为空',
                    'user_login.unique'  => '账户名已存在',
                    'user_pass.require'  => '密码不能为空',
                    'user_email.require' => '邮箱不能为空',
                    'user_email.email'   => '邮箱不正确',
                    'user_email.unique'  => '邮箱已经存在',
                ];
                $validate = Validate::make($rule,$message);
                $result = $validate->check($this->request->param());

                if ($result !== true) {
                    return $this->error('添加'.$validate->getError());
                } else {
                    $tenant['tenant_type'] = $_POST['tenant_type'];
                    $tenant['tenant_id'] = $admin['tenant_id']==0?0:$admin['tenant_id'];//新增商户的父级还是商户主管理员

                    $tenant['user_login'] = $_POST['user_login'];
                    $tenant['user_nickname'] = $_POST['user_nickname'];
                    $tenant['user_pass'] = cmf_password($_POST['user_pass']);
                    $tenant['user_email'] = $_POST['user_email'];

                    $user_id             = DB::name('user')->insertGetId($tenant);
                    if ($user_id !== false) {
                        $user = ['role_id'=>3,'user_id'=>$user_id];
                        $roleAdd =  DB::name('role_user')->insertGetId($user);
                        if($roleAdd){
                            //更新入驻订单状态
                            //生成二维码链接存入店铺
                            $shopInfoModel = new ShopInfoModel();
                            $shop  = $shopInfoModel->getOne($_POST['order_id']);

                            $shop_host = Db::name('system_setting')->where('key_name','tenant_host')->value('value_name');
                            if(strpos($shop_host,'?')!==false){
                                $url = $shop_host.'&shop_id='.$shop['shop_id'];
                            }else{
                                $url = $shop_host.'?shop_id='.$shop['shop_id'];
                            }

                            $qrcode = new PhpQrcodePlugin();
                            $content = [
                                'content' => $url
                            ];
                            $res = $qrcode->createQRcode($content);
                            
                            $data =[
                                'qrcode'=>empty($res['preview_url'])?'':$res['preview_url'],
                                'checked'=>1,
                                'status'=>1

                            ];
                            //更新店铺审核状态
                            ShopInfoModel::where('id',$_POST['order_id'])->update($data);
                            //更新开店申请关联表管理员id
                            Db::name('shop_apply_order')->where('shop_info_id',$_POST['order_id'])->update(['user_id'=>$user_id]);
                            $this->success("添加成功！");
                        }else {
                            $this->error("添加失败！");
                        }
                    } else {
                        $this->error("添加失败！");
                    }
                }
            

        }
    }


}